#ifndef NETSENDRECEIVE_H
#define NETSENDRECEIVE_H

#include <QObject>

QT_BEGIN_NAMESPACE
class QUdpSocket;
QT_END_NAMESPACE

#define NET_HEADER1 0x7d
#define NET_HEADER2 0x7b
#define NET_TAIL1 0x7d
#define NET_TAIL2 0x7d
#define NET_ADDRESS_LOCAL 0xf3
#define NET_ADDRESS_MS 0xf5//0xf5
#define NET_ADDRESS_LENGTH 1

typedef struct _NetDataPacket
{
    unsigned char header1;//FA
    unsigned char header2;//F5
    unsigned char destAddressLength;//1
    unsigned char destAddress;
    unsigned char sourceAddressLength;//1
    unsigned char sourceAddress;
    unsigned char cmd1;
    unsigned char cmd2;
    unsigned short length;//0-65535
    QByteArray data;
    unsigned short cs;
    unsigned char tail1;
    unsigned char tail2;
}NetDataPacket;

class NetSendReceive : public QObject
{
    Q_OBJECT
public:
    explicit NetSendReceive(QObject *parent = 0);

    enum Time
    {
        TIMEOUT_SEND=500
    };

    bool SendData(QByteArray sendData);
    bool SendData(NetDataPacket sendData,NetDataPacket &receiveData);

    void SetSocket(QString localIp="192.168.2.230",int localPort=20000,QString destIp="192.168.2.230",int destPort=30000);
    void ReInit();

private:
    QUdpSocket *udpSocketSend;
    QUdpSocket *udpSocketRecv;
    NetDataPacket sendPacket;
    NetDataPacket recvPacket;
    QString localIp;
    int localPort;
    QString destIp;
    int destPort;


    bool Check(QByteArray datagram);
    ushort  Crc(QByteArray datagram);
    void Decode(QByteArray datagram);
    void Encode(QByteArray datagram);

    bool ReceiveData(NetDataPacket &receiveData);
signals:
    void SIG_ReceiveData(NetDataPacket receiveData);
public slots:
    bool ProcessPendingDatagrams();
};

#endif // NETSENDRECEIVE_H
